// page/mall/pages/poster/poster.js
var app = getApp(),
  that;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: {},
    listLabel: [],
    id: '',
    title: '',
    category: {},
    maskHidden: false,
    word: '长按二维码识别小程序',
    head: '大昌车管家',
    di1: "../../../../image/di1.png",
    di2: "../../../../image/di2.png",
    di3: "../../../../image/di3.png",
    picture: '',
    qrcode: '',
    filePath: ''
  },
  handleLongPress: function(e) {
    console.log("长按");
    wx.navigateTo({
      url: `/page/package/pages/shopDetail/shopDetail?id=${that.data.id}&title=${that.data.mername}`,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    that = this
    that.data.id = options.id
    that.data.title = options.title
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  // 获取二维码
  getCode: function() {
    var that = this
    app.getData({
      url: app.api.shareCommodity() + `?id=${that.data.id}`,
      ok: function(res) {
        console.log(res)
        if (res.statusCode == 200 && res.errMsg == 'request:ok') {
          if (res.data.code == 1) {
            that.setData({
              category: res.data.data,
              picture: res.data.data.image,
              qrcode: res.data.data.qrcode
            })
            wx.setStorageSync("picture", res.data.data.image)
            wx.setStorageSync("qrcode", res.data.data.qrcode)
          }
        }
      }
    })
  },
  //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
  createNewImg: function() {
    var that = this;
    // var path1 = that.data.picture;
    var path1 = '';
    // var path2 = that.data.qrcode;
    var path2 = '';
    // path1 = that.getTemPath(wx.getStorageSync("picture"));
    // path2 = that.getTemPath(wx.getStorageSync("qrcode"));
    wx.getImageInfo({
      src: wx.getStorageSync("picture"),
      success: function(res) {
        console.log(res.path) //打印图片的本地路径
        path1 = res.path;
        wx.getImageInfo({
          src: wx.getStorageSync("qrcode"),
          success: function(res) {
            console.log(res.path) //打印图片的本地路径
            path2 = res.path;
            console.log(path1);
            console.log(path2);
            that.kTest(path1, path2);

          }
        })
      }
    })
  },
  kTest: function(path1, path2) {
    var path3 = that.data.di1;
    var path4 = that.data.di2;
    var path5 = that.data.di3;
    console.log(path1);
    console.log(path2);
    var context = wx.createCanvasContext('myCanvas');
    // 填充颜色
    context.setFillStyle("#fff")
    // 填充一个矩形
    context.fillRect(0, 0, 375, 667)
    //绘制标题
    var head = that.data.head;
    context.setFontSize(26);
    context.setFillStyle('#000');
    context.setTextAlign('center');
    context.fillText(head, 190, 50);
    context.stroke();

    //绘制商品
    context.drawImage(path1, 100, 70, 180, 220);
    //绘制车名
    var name = that.data.category.parductName
    // context.setFontSize(20);
    // context.setFillStyle('#000');
    // context.setTextAlign('left');
    // context.fillText(name, 40, 330);

    console.log(that.data.category.parductName)

    var chr = name.split(""); //这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    context.setFontSize(18)
    context.setFillStyle("#000")
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < 250) {
        temp += chr[a];
      } else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);
    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < 220) {
          test += rowPart[a];
        } else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..." //这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      context.fillText(row[b], 180, 340 + b * 30, 340);
    }
    context.setTextAlign('left')
    context.stroke();

    //绘制最低价￥
    var text = that.data.category.parductSalesPrice
    context.setFontSize(20);
    context.setFillStyle('#000');
    context.setTextAlign('left');
    context.fillText('最低价￥' + text, 70, 410);
    context.stroke();
    //绘制原价￥
    var text = that.data.category.parductPrimaryPrice
    context.setFontSize(18);
    context.setFillStyle('#000');
    context.setTextAlign('left');
    context.moveTo(210, 404);
    context.lineTo(290, 404);
    context.setLineWidth(2)
    context.setStrokeStyle('red')
    context.fillText('原价￥' + text, 210, 410);
    context.stroke();
    //绘制标签
    // context.drawImage(path3, 40, 300, 38, 28);
    // var text1 = that.data.category.listLabel[0].labelName;
    // context.setFontSize(14);
    // context.setFillStyle('#fff');
    // context.setTextAlign('left');
    // context.fillText(text1, 46, 320);
    // context.stroke();

    // context.drawImage(path4, 90, 300, 38, 28);
    // var text1 = that.data.category.listLabel[1].labelName;
    // context.setFontSize(14);
    // context.setFillStyle('#fff');
    // context.setTextAlign('left');
    // context.fillText(text1, 96, 320);
    // context.stroke();

    // context.drawImage(path5, 140, 300, 38, 28);
    // var text1 = that.data.category.listLabel[2].labelName;
    // context.setFontSize(14);
    // context.setFillStyle('#fff');
    // context.setTextAlign('left');
    // context.fillText(text1, 146, 320);
    // context.stroke();

    //绘制分割线
    context.moveTo(30, 380);
    context.lineTo(350, 380);
    context.setStrokeStyle('#e5e5e5');
    context.setLineWidth(1)
    context.stroke()

    //绘制二维码
    context.drawImage(path2, 110, 440, 150, 150);

    // 绘制底部文字
    var word = that.data.word
    context.setFontSize(20);
    context.setFillStyle('#000');
    context.setTextAlign('center');
    context.fillText(word, 185, 640);
    context.stroke();

    context.draw(true, setTimeout(function() {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function(res) {
          // that.data.imagePath = res.tempFilePath
          that.setData({
            imagePath: res.tempFilePath,
            canvasHidden: true
          });
        },
      })
    }, 1000));

    // context.draw();
    // // that.seave();
    // setTimeout(function() {
    //   wx.canvasToTempFilePath({
    //     canvasId: 'myCanvas',
    //     success: function(res) {
    //       console.log(res)
    //       var tempFilePath = res.tempFilePath;
    //       that.setData({
    //         imagePath: tempFilePath,
    //         canvasHidden: true
    //       });
    //     },
    //     fail: function(res) {
    //       console.log(res);
    //     }
    //   });
    // }, 2000);
  },
  getTemPath: function(httpPath) {
    wx.getImageInfo({
      src: httpPath,
      success: function(res) {
        console.log(res.path) //打印图片的本地路径
        ph = res.path;
      }
    })
  },

  // fff: function(context, oldPath, x, y, w, h, callBack) {
  //   wx.downloadFile({
  //     url: oldPath,
  //     success: function(res) {
  //       console.log(res)
  //       if (res.statusCode === 200) {
  //         wx.getImageInfo({
  //           src: res.tempFilePath,
  //           success: function(res) {
  //             console.log(res) //打印图片的本地路径
  //             //绘制头像
  //             context.drawImage(res.path, x, y, w, h);
  //             callBack();
  //           }
  //         })
  //       }
  //     }
  //   })
  // },
  //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
  serve: function() {
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function(res) {
        console.log(res)
        var tempFilePath = res.tempFilePath;
        that.setData({
          imagePath: tempFilePath,
          canvasHidden: true
        });
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //点击保存到相册
  baocun: function() {
    var that = this
    console.log(that.data.imagePath)
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        console.log(res)
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
              that.setData({
                maskHidden: false
              })
            }
          },
          fail: function(res) {
            console.log(11111)
          }
        })
      }
    })
  },
  //点击生成
  formSubmit: function() {

    var that = this;
    this.setData({
      maskHidden: false
    });
    wx.showToast({
      title: '生成中...',
      icon: 'loading',
      duration: 1000
    });
    setTimeout(function() {
      wx.hideToast()
      that.createNewImg();
      that.setData({
        maskHidden: true
      });
    }, 1000)



    // setTimeout(function () {
    //   wx.canvasToTempFilePath({
    //     canvasId: 'myCanvas',
    //     success(res) {
    //       console.log(res)
    //       wx.authorize({
    //         scope: 'scope.writePhotosAlbum',
    //         success() {
    //           wx.saveImageToPhotosAlbum({
    //             filePath: res.tempFilePath,
    //             success() {
    //               wx.showToast({
    //                 title: '图片保存成功'
    //               })
    //             }
    //           })
    //         }
    //       })
    //     }
    //   }, this)
    // }, 2000);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getCode()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})